package com.xiaohong.seckill.mq.listener;


import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.xiaohong.seckill.service.SeckillOrderService;
import entity.HttpClient;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RabbitListener(queues = "${mq.pay.queue.seckillorder}")
//@RabbitListener(queues = "queue.seckillorder")
public class MqListener {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 接收消息
     */
    @RabbitHandler
    public void consumeMessage(String msg) throws Exception {
        //将数据转成Map
        Map<String,String> result = JSON.parseObject(msg,Map.class);

        //通信标识 return_code=SUCCESS
        String return_code = result.get("return_code");
        //业务结果
        String result_code = result.get("result_code");
        //获取用户用户名
        String attach = result.get("attach");
        Map<String,String> attachMap = JSON.parseObject(attach, Map.class);
        String username = attachMap.get("username");
        //商品订单号
        String outtradeno = null;

        //业务结果 result_code=SUCCESS/FAIL，修改订单状态
        if(return_code.equalsIgnoreCase("success") ){
            //获取订单号
            outtradeno= result.get("out_trade_no");
            //业务结果
            if(result_code.equalsIgnoreCase("success")){
                if(outtradeno!=null){
                    //修改订单状态  out_trade_no
//                    seckillOrderService.updateStatus(outtradeno,result.get("transaction_id"),result.get("time_end"),username);
                }
            }else{
                //取消订单
                //1.封装参数
                Map param = new HashMap();
                param.put("appid",appid);                            //应用ID
                param.put("mch_id",partner);                         //商户号
                param.put("out_trade_no",outtradeno);                //商户订单编号
                param.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符
                param.put("sign", "xiaohong");                        //签名

                //2、将参数转成xml字符，并携带签名
                String paramXml = null;

                paramXml = WXPayUtil.generateSignedXml(param,partnerkey);


                //3、发送请求
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/closeorder");
                httpClient.setHttps(true);
                httpClient.setXmlParam(paramXml);
                httpClient.post();

                //4、获取返回值，并将返回值转成Map
                String content = httpClient.getContent();
                Map<String, String> stringMap = WXPayUtil.xmlToMap(content);
                //判断关闭订单是否成功
                if (stringMap.get("return_code").equalsIgnoreCase("success")){
                    //关闭订单成功
                    //订单删除(逻辑删除)
//                    seckillOrderService.deletOrder(outtradeno,username);
                }else if (stringMap.get("return_code").equalsIgnoreCase("ORDERPAID")){
                    //关闭订单失败 原因：已支付
                    //查询支付状态并修改订单状态  out_trade_no
                    HttpClient httpClient2 = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
                    httpClient2.setHttps(true);
                    httpClient2.setXmlParam(paramXml);
                    httpClient2.post();
                    //获取返回值，并将返回值转成Map
                    String content2 = httpClient.getContent();
                    Map<String, String> stringMap2 = WXPayUtil.xmlToMap(content2);
//                    seckillOrderService.updateStatus(outtradeno,stringMap2.get("transaction_id"),stringMap2.get("time_end"),username);
                }else {
                    //关闭订单失败 原因：其他错误
                    //订单回滚(逻辑删除)
//                    seckillOrderService.deletOrder(outtradeno,username);
                }

            }
        }
    }
}
